package com.zh.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zh.common.BaseContext;
import com.zh.common.Result;
import com.zh.entity.ShoppingCart;
import com.zh.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author 你爹
 * @since 2023-09-21
 */
@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @GetMapping("/list")
    public Result<List<ShoppingCart>> list(){
        LambdaUpdateWrapper<ShoppingCart> wrapper =new LambdaUpdateWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        wrapper.orderByDesc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(wrapper);
        return Result.success(shoppingCartList);
    }
    @PostMapping("/add")
    public Result<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        log.info("shoppingCart:{}",shoppingCart);
        ShoppingCart cart = shoppingCartService.saveOrAdd(shoppingCart);
        return Result.success(cart);
    }
    @PostMapping("/sub")
    public Result<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){
        log.info("shoppingCart:{}",shoppingCart);
        ShoppingCart cart = shoppingCartService.subOrRemove(shoppingCart);
        return Result.success(cart);
    }

    @DeleteMapping("/clean")
    public Result clean(){
        Long userId = BaseContext.getCurrentId();
        log.info("userId:{}",userId);
        LambdaUpdateWrapper<ShoppingCart> wrapper =new LambdaUpdateWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(wrapper);
        return Result.success("清空购物车成功");
    }
}
